package cn.hnu.qq.client.controller;

import java.io.IOException;
import java.net.DatagramPacket;
import java.util.Vector;

import cn.hnu.qq.client.event.MessageEvent;
import cn.hnu.qq.client.listener.MessageListener;
import cn.hnu.qq.entity.message.Message;

public class ListenClientMessageThread extends CenterController implements Runnable{
	
	private static ListenClientMessageThread instance = null;
	
	private ListenClientMessageThread(){};
	
	private Vector<MessageListener> listeners = new Vector<MessageListener>();
	
	public static synchronized ListenClientMessageThread getInstance(){
		if(instance == null){
			instance = new ListenClientMessageThread();
		}
		return instance;
	}
	public void run() {
		while(true){
			byte[] buf = new byte[1024]; //设定缓存1024 表示发送字节小于1024byte 一次，即汉字小于500字 
			DatagramPacket dp = new DatagramPacket(buf, buf.length);
			try {
				getdSocket().receive(dp);
				log.debug("客户端接收数据长度："+dp.getLength());
				log.debug("字符串长度："+dp.getData().length);
				log.debug("终止位置："+dp.getOffset());
				
				Message message = (Message) ArrayToObject(dp.getData(),dp.getLength());
				switch(message.getMessageType()){
				case CHART:
				case CROWD_CHART:
				case SEND_FILE:
					handleChartMessage(message);
					break;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private synchronized void handleChartMessage(Message message) {
		log.debug("处理聊天消息 :　"+ message);
		MessageEvent event = new MessageEvent(message);
		log.debug("监听器      ： " + listeners);
		/*
		 * 不适用for each的原因是解决在迭代的同时修改监听器表
		 */
		int i = listeners.size() - 1;
		for(;i>=0;i--){
			listeners.get(i).messageArrived(event);
		}
	}
	
	public synchronized void addMessageListener(MessageListener ml){
		for(MessageListener mm : listeners){
			if(mm.equals(ml)){
				return;
			}
		}
		listeners.add(ml);
	}
	
	public synchronized void removeMessageListener(MessageListener ml){
		listeners.remove(ml);
	}
	
	public synchronized void removeAllListener(){
		listeners.removeAllElements();
	}
}
